import datetime

from django.contrib.auth.models import AnonymousUser
from django.db import transaction
from django.db.models import Q
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import status, mixins
from rest_framework.decorators import action
from rest_framework.filters import OrderingFilter
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet, GenericViewSet
from apps.club_system.club.filters import ClubApplicationFilter
from apps.club_system.club.models import ClubApplication, Club, ClubMember, Log
from apps.club_system.club.serializers.club_application import ClubApplicationSerializer, \
    ClubApplicationDetailSerializer
from utils.common import Pagination


class ClubApplicationViewSet(mixins.CreateModelMixin,
                             mixins.RetrieveModelMixin,
                             mixins.DestroyModelMixin,
                             mixins.ListModelMixin,
                             GenericViewSet):
    '''申请加入社团表视图'''
    queryset = ClubApplication.objects.select_related('club', 'account').filter(is_active=True)
    filter_backends = (OrderingFilter, DjangoFilterBackend)
    pagination_class = Pagination
    filter_class = ClubApplicationFilter
    serializer_class = ClubApplicationDetailSerializer
    ordering_fields = ('id', 'created_time')

    def list(self, request, *args, **kwargs):

        if request.user.is_admin() or request.user.is_role('club_school_manager'):
            queryset = self.get_queryset()
        elif request.user.is_chairman_manager() or request.user.is_teacher_manager():
            club_ids = ClubMember.objects.filter(account=request.user, role__in=[3, 4], is_active=True)\
                .values_list('club_id', flat=True)
            queryset = self.get_queryset().filter(Q(club_id__in=club_ids) | Q(account=request.user))
        else:
            queryset = self.get_queryset().filter(account=request.user)
        queryset=self.filter_queryset(queryset)
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        if instance.first_check_status == '通过' or instance.second_check_status == '通过':
            return Response({'message': '无法删除'}, status=status.HTTP_400_BAD_REQUEST)
        if request.user.id == instance.account.id:
            instance.is_active = False
        else:
            return Response({'message': '无权限删除此数据！'}, status=status.HTTP_400_BAD_REQUEST)
        instance.save()
        Log.objects.create(username=request.user.username, name=request.user.realname, operate_type=3,
                           table_name='ClubApplication', comment=f'删除了社团报名',
                           detail=f'社团名称是{instance.club.name}')
        return Response({'message': '删除成功'}, status=status.HTTP_204_NO_CONTENT)

    def create(self, request, *args, **kwargs):
        club_id = request.data.get('club_id')
        account_id = request.user.id
        if not club_id:
            return Response({'message': '必须有报名的社团'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            club = Club.objects.get(id=club_id, first_check_status='通过', second_check_status='通过', is_active=True)
            now_time = datetime.datetime.now()
            if not club.apply_start_time or not club.apply_end_time:
                return Response({'message': '当前不在报名时间内'}, status=status.HTTP_400_BAD_REQUEST)
            if now_time < club.apply_start_time or now_time > club.apply_end_time:
                return Response({'message': '当前不在报名时间内'}, status=status.HTTP_400_BAD_REQUEST)
        except Club.DoesNotExist:
            return Response({'message': '无效的社团id'}, status=status.HTTP_400_BAD_REQUEST)
        application = ClubApplication.objects.filter(account_id=account_id, club=club, is_active=True)\
            .exclude(Q(first_check_status='不通过') | Q(second_check_status='不通过')).exists()
        if application:
            return Response({'message': "你已报名该社团，请勿重复报名！"}, status=status.HTTP_400_BAD_REQUEST)

        exists = ClubMember.objects.filter(account=account_id, club_id=club_id, is_active=True).exists()
        if exists:
            return Response({'message': "你已是该社团成员！"}, status=status.HTTP_400_BAD_REQUEST)

        apply_club_count = ClubApplication.objects.filter(account_id=account_id, first_check_status__in=['待审核', '通过'],
                                                          second_check_status='待审核', is_active=True).count()
        club_member_count = ClubMember.objects.filter(account_id=account_id, is_active=True).count()
        if apply_club_count + club_member_count >= 2:
            return Response({'message': '每人最多加入或报名两个社团！'}, status=status.HTTP_400_BAD_REQUEST)

        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        Log.objects.create(username=request.user.username, name=request.user.realname, operate_type=1,
                           table_name='ClubApplication', comment=f'新增了社团报名',
                           detail=f'报名社团{club.name}')
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    # def update(self, request, *args, **kwargs):
    #     partial = kwargs.pop('partial', False)
    #     instance = self.get_object()
    #     if instance.first_check_status == '通过' and instance.second_check_status in ['通过', '待审核']:
    #         return Response({'message': '已审核通过不可再做修改'}, status=status.HTTP_400_BAD_REQUEST)
    #     if instance.account != request.user:
    #         return Response({'message': '只有该社团报名的创建者才能修改！'}, status=status.HTTP_400_BAD_REQUEST)
    #     serializer = self.get_serializer(instance, data=request.data, partial=partial)
    #     serializer.is_valid(raise_exception=True)
    #     try:
    #         serializer.save()
    #     except Exception as e:
    #         return Response({'message': e.args}, status=status.HTTP_400_BAD_REQUEST)
    #     if getattr(instance, '_prefetched_objects_cache', None):
    #         instance._prefetched_objects_cache = {}
    #     Log.objects.create(username=request.user.username, name=request.user.realname, operate_type=2,
    #                        table_name='ClubApplication', comment=f'修改了社团报名',
    #                        detail=f'社团名称是{instance.club.name}')
    #     return Response(serializer.data)

    @action(methods=['get'], detail=False, url_path='first_check_list')
    def first_check_list(self, request, *args, **kwargs):
        """  获取一级待审核的数据 """
        if request.user.is_admin():
            queryset = ClubApplication.objects.select_related('club', 'account') \
                .filter(first_check_status='待审核', second_check_status='待审核', is_active=True)
        else:
            account_id = request.user.id
            values = ClubMember.objects.filter(account_id=account_id, is_active=True, role=3) \
                .values_list('club_id', flat=True)
            queryset = ClubApplication.objects.select_related('club', 'account') \
                .filter(club_id__in=list(values), first_check_status='待审核', second_check_status='待审核', is_active=True)
        queryset = self.filter_queryset(queryset)
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = ClubApplicationSerializer(page, many=True, context={'request': request})
            return self.get_paginated_response(serializer.data)
        serializer = ClubApplicationSerializer(queryset, many=True, context={'request': request})
        return Response(serializer.data)

    @action(methods=['get'], detail=False, url_path='second_check_list')
    def second_check_list(self, request, *args, **kwargs):
        """  获取二级待审核的数据 """
        queryset = ClubApplication.objects.select_related('club', 'account') \
            .filter(first_check_status='通过', second_check_status='待审核', is_active=True)
        queryset = self.filter_queryset(queryset)
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = ClubApplicationSerializer(page, many=True, context={'request': request})
            return self.get_paginated_response(serializer.data)
        serializer = ClubApplicationSerializer(queryset, many=True, context={'request': request})
        return Response(serializer.data)

    @action(methods=['post'], detail=True, url_path='first_check')
    def first_check(self, request, pk=None):
        """ 进行一级审核 """
        check_status = request.data.get('check_status', '')

        if check_status not in ('通过', '不通过'):
            return Response({'message': '缺少审核状态或者审核状态错误'}, status=status.HTTP_400_BAD_REQUEST)
        if not request.user.is_admin() and not request.user.is_chairman_manager():
            return Response({'message': '您无权限进行审核！'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            instance = ClubApplication.objects.only('id').get(id=pk)
        except ClubApplication.DoesNotExist:
            return Response({'message': '错误的参数'}, status=status.HTTP_400_BAD_REQUEST)
        instance.first_check_status = check_status
        instance.save()
        Log.objects.create(username=request.user.username, name=request.user.realname, operate_type=4,
                           table_name='ClubApplication', comment=f'审核了社团名为{instance.club.name},'
                                                                 f'申请人为{instance.account.realname}的报名社团记录',
                           detail=f'审核状态为{check_status}, 为一级审核')
        return Response({'message': '审核成功'}, status=status.HTTP_200_OK)

    @action(methods=['post'], detail=True, url_path='second_check')
    def second_check(self, request, pk=None):
        """ 进行二级审核 """
        check_status = request.data.get('check_status', '')
        if check_status not in ('通过', '不通过'):
            return Response({'message': '缺少审核状态或者审核状态错误'}, status=status.HTTP_400_BAD_REQUEST)
        if not request.user.is_admin() and not request.user.is_role('club_school_manager'):
            return Response({'message': '您无权限进行审核！'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            instance = ClubApplication.objects.only('id').get(id=pk)
        except ClubApplication.DoesNotExist:
            return Response({'message': '错误的参数'}, status=status.HTTP_400_BAD_REQUEST)
        if check_status == '通过':
            ClubMember.objects.create(account_id=instance.account_id, club_id=instance.club_id)
        instance.second_check_status = check_status
        instance.save()
        Log.objects.create(username=request.user.username, name=request.user.realname, operate_type=4,
                          table_name='ClubApplication', comment=f'审核了社团名为{instance.club.name},'
                                                                f'申请人为{instance.account.realname}的报名社团记录',
                          detail=f'审核状态为{check_status}, 为二级审核')
        return Response({'message': '审核成功'}, status=status.HTTP_200_OK)

    # @action(methods=['get'], detail=False, url_path='myappliaction')
    # def get_myappliaction(self, request):
    #     account_id = request.user.id
    #     queryset = self.filter_queryset(self.get_queryset().filter(account_id=account_id))
    #     page = self.paginate_queryset(queryset)
    #     if page is not None:
    #         serializer = ClubApplicationDetailSerializer(page, many=True, context={'request': request})
    #         return self.get_paginated_response(serializer.data)
    #     serializer = ClubApplicationDetailSerializer(queryset, many=True, context={'request': request})
    #     return Response(serializer.data)



